package com.cby.library.common.network

import android.util.Log
import okhttp3.Interceptor
import okhttp3.Response
import java.text.SimpleDateFormat
import java.util.*

/**
 * 数据请求的日志拦截器
 *
 * @author ChenBaoYang
 */
class LogInterceptor : Interceptor {

    private val tag = "retrofit"
    private val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")

    override fun intercept(chain: Interceptor.Chain): Response {

        val request = chain.request()
        Log.i(
            tag,
            "${format.format(Date())}  Request \nmethod: ${request.method} \nurl: ${request.url} \nbody: ${request.body}"
        )

        val response = chain.proceed(request)
        //response.peekBody不会关闭流
        Log.i(
            tag,
            "${format.format(Date())}  Response \nsuccessful: ${response.isSuccessful} \nbody: ${
                response.peekBody(1024).string()
            }"
        )

        return response
    }
}